# -*- coding: utf-8 -*-
"""
最终智能化服务器 - 使用真实高铁数据
"""
from flask import Flask, jsonify, request, render_template_string
from flask_cors import CORS
import requests
import json
import pandas as pd
import os
from datetime import datetime, timedelta
import openai
import sys

app = Flask(__name__)
CORS(app)

# API配置
DEEPSEEK_API_KEY = "sk-00d9e28b0be74eb4b070a062b7cb73b7"
DEEPSEEK_BASE_URL = "https://api.deepseek.com/v1"
DEEPSEEK_MODEL = "deepseek-chat"
GAODE_API_KEY = "003df4ac18f1cca97eaf59dc90afbaa2"

# 聚合数据API配置
JUHE_FLIGHT_APPKEY = "b0daee5c7cf963ae6458020601583575"
JUHE_TRAIN_APPKEY = "5d11310f7cfa2c69ad50641bc3cf0288"

# 城市到IATA机场代码映射
CITY_TO_IATA = {
    '北京': 'BJS', '上海': 'SHA', '广州': 'CAN', '深圳': 'SZX',
    '大连': 'DLC', '合肥': 'HFE', '南京': 'NKG', '杭州': 'HGH',
    '武汉': 'WUH', '成都': 'CTU', '重庆': 'CKG', '西安': 'SIA',
    '天津': 'TSN', '青岛': 'TAO', '沈阳': 'SHE', '哈尔滨': 'HRB',
    '厦门': 'XMN', '福州': 'FOC', '长沙': 'CSX', '郑州': 'CGO',
    '济南': 'TNA', '太原': 'TYN', '石家庄': 'SJW', '呼和浩特': 'HET',
    '兰州': 'LHW', '银川': 'INC', '西宁': 'XNN', '乌鲁木齐': 'URC',
    '拉萨': 'LXA', '昆明': 'KMG', '贵阳': 'KWE', '南宁': 'NNG',
    '海口': 'HAK', '三亚': 'SYX'
}

# 城市到12306车站名映射
CITY_TO_STATION = {
    '北京': '北京', '上海': '上海', '广州': '广州', '深圳': '深圳',
    '大连': '大连北', '合肥': '合肥南', '南京': '南京南', '杭州': '杭州东',
    '武汉': '武汉', '成都': '成都东', '重庆': '重庆北', '西安': '西安北',
    '天津': '天津', '青岛': '青岛', '沈阳': '沈阳', '哈尔滨': '哈尔滨西',
    '厦门': '厦门北', '福州': '福州', '长沙': '长沙南', '郑州': '郑州东',
    '济南': '济南西', '太原': '太原南', '石家庄': '石家庄', '呼和浩特': '呼和浩特',
    '兰州': '兰州西', '银川': '银川', '西宁': '西宁', '乌鲁木齐': '乌鲁木齐',
    '拉萨': '拉萨', '昆明': '昆明南', '贵阳': '贵阳北', '南宁': '南宁',
    '海口': '海口', '三亚': '三亚'
}

# 周边城市映射（用于智能对比）
NEARBY_CITIES = {
    '大连': ['沈阳', '营口', '丹东', '鞍山'],
    '合肥': ['南京', '武汉', '郑州', '济南'],
    '北京': ['天津', '石家庄', '保定', '廊坊'],
    '上海': ['南京', '杭州', '苏州', '无锡'],
    '广州': ['深圳', '佛山', '东莞', '中山'],
    '深圳': ['广州', '东莞', '惠州', '佛山'],
    '南京': ['上海', '合肥', '苏州', '无锡'],
    '杭州': ['上海', '南京', '宁波', '绍兴'],
    '武汉': ['长沙', '郑州', '合肥', '南昌'],
    '成都': ['重庆', '西安', '贵阳', '昆明'],
    '重庆': ['成都', '贵阳', '西安', '武汉'],
    '西安': ['郑州', '太原', '兰州', '成都'],
    '天津': ['北京', '石家庄', '唐山', '保定'],
    '青岛': ['济南', '烟台', '威海', '潍坊'],
    '沈阳': ['大连', '长春', '哈尔滨', '鞍山'],
    '哈尔滨': ['长春', '沈阳', '大庆', '齐齐哈尔']
}

class FinalSmartTravelAPI:
    def __init__(self):
        self.gaode_key = GAODE_API_KEY
        self.base_url = "https://restapi.amap.com/v3"
        
        # 初始化DeepSeek AI客户端
        try:
            if hasattr(openai, 'OpenAI'):
                self.ai_client = openai.OpenAI(
                    api_key=DEEPSEEK_API_KEY,
                    base_url=DEEPSEEK_BASE_URL
                )
                self.ai_available = True
                self.use_new_client = True
                print("✅ DeepSeek AI 客户端初始化成功")
            else:
                openai.api_key = DEEPSEEK_API_KEY
                openai.api_base = DEEPSEEK_BASE_URL
                self.ai_available = True
                self.use_new_client = False
                print("✅ DeepSeek AI 客户端初始化成功 (旧版本)")
        except Exception as e:
            print(f"❌ DeepSeek AI 客户端初始化失败: {e}")
            self.ai_available = False
        
        # 加载本地高铁数据
        self.train_data = self._load_local_train_data()
    
    def _load_local_train_data(self):
        """加载本地高铁数据"""
        train_data = []
        
        # 尝试从Excel文件加载
        excel_files = [
            '../全国高铁区间票价明细表_去重版.xlsx',
            '全国高铁区间票价明细表_去重版.xlsx',
            '../crawler_lab/全国高铁区间票价明细表_去重版.xlsx'
        ]
        
        for excel_file in excel_files:
            if os.path.exists(excel_file):
                try:
                    print(f"📊 尝试加载Excel文件: {excel_file}")
                    df = pd.read_excel(excel_file)
                    print(f"📊 从 {excel_file} 加载了 {len(df)} 条数据")
                    print(f"📋 列名: {list(df.columns)}")
                    
                    # 转换为统一格式
                    for _, row in df.iterrows():
                        try:
                            # 根据实际列名调整
                            origin = str(row.get('出发站', row.get('出发地', row.get('起点', ''))))
                            destination = str(row.get('到达站', row.get('目的地', row.get('终点', ''))))
                            price = row.get('票价', row.get('价格', row.get('二等座', 0)))
                            train_no = row.get('车次', row.get('列车号', row.get('车次号', '')))
                            
                            if origin and destination and price:
                                train_data.append({
                                    'type': 'train',
                                    'train_number': str(train_no) if train_no else 'G' + str(len(train_data) + 1).zfill(4),
                                    'train_type': '高铁',
                                    'origin': origin,
                                    'destination': destination,
                                    'dep_time': '2025-09-20 08:00',  # 默认时间
                                    'arr_time': '2025-09-20 16:00',  # 默认时间
                                    'price': int(float(price)) if price else 0,
                                    'dep_station': origin,
                                    'arr_station': destination,
                                    'duration': '8小时',  # 默认时长
                                    'seat_type': '二等座',
                                    'is_high_speed': '是',
                                    'source': '本地Excel数据',
                                    'crawl_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                                })
                        except Exception as e:
                            print(f"  ❌ 解析Excel行异常: {e}")
                            continue
                    
                    break  # 成功加载一个文件就退出
                    
                except Exception as e:
                    print(f"❌ 加载Excel文件失败: {e}")
                    continue
        
        # 如果没有找到数据，生成一些示例高铁数据
        if not train_data:
            print("📝 生成示例高铁数据")
            train_data = self._generate_sample_train_data()
        
        print(f"✅ 加载了 {len(train_data)} 条高铁数据")
        return train_data
    
    def _generate_sample_train_data(self):
        """生成示例高铁数据"""
        sample_data = [
            {
                'type': 'train',
                'train_number': 'G1234',
                'train_type': '高铁',
                'origin': '大连',
                'destination': '合肥',
                'dep_time': '2025-09-20 08:30',
                'arr_time': '2025-09-20 16:45',
                'price': 580,
                'dep_station': '大连北站',
                'arr_station': '合肥南站',
                'duration': '8小时15分',
                'seat_type': '二等座',
                'is_high_speed': '是',
                'source': '示例数据',
                'crawl_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            },
            {
                'type': 'train',
                'train_number': 'G5678',
                'train_type': '高铁',
                'origin': '大连',
                'destination': '合肥',
                'dep_time': '2025-09-20 14:20',
                'arr_time': '2025-09-20 22:35',
                'price': 620,
                'dep_station': '大连北站',
                'arr_station': '合肥南站',
                'duration': '8小时15分',
                'seat_type': '二等座',
                'is_high_speed': '是',
                'source': '示例数据',
                'crawl_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            },
            {
                'type': 'train',
                'train_number': 'G9999',
                'train_type': '高铁',
                'origin': '沈阳',
                'destination': '合肥',
                'dep_time': '2025-09-20 09:15',
                'arr_time': '2025-09-20 17:30',
                'price': 520,
                'dep_station': '沈阳站',
                'arr_station': '合肥南站',
                'duration': '8小时15分',
                'seat_type': '二等座',
                'is_high_speed': '是',
                'source': '示例数据',
                'crawl_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            }
        ]
        return sample_data
    
    def get_flight_data(self, origin, destination, date=None):
        """获取机票数据"""
        if not date:
            date = (datetime.now() + timedelta(days=1)).strftime('%Y-%m-%d')
        
        print(f"🔍 获取机票数据: {origin} → {destination} ({date})")
        
        try:
            from_code = CITY_TO_IATA.get(origin, origin)
            to_code = CITY_TO_IATA.get(destination, destination)
            
            url = "https://apis.juhe.cn/flight/query"
            params = {
                'key': JUHE_FLIGHT_APPKEY,
                'dtype': 'json',
                'departure': from_code,
                'arrival': to_code,
                'departureDate': date
            }
            
            response = requests.get(url, params=params, timeout=15)
            
            if response.status_code == 200:
                result = response.json()
                if result.get('error_code') == 0:
                    flights = self._parse_flight_data(result, origin, destination)
                    print(f"✅ 获取到 {len(flights)} 条机票数据")
                    return flights
            
            print(f"❌ 机票API错误: {result.get('reason', '未知')}")
            return []
                
        except Exception as e:
            print(f"❌ 机票API异常: {e}")
            return []
    
    def get_train_data(self, origin, destination, date=None):
        """获取火车票数据 - 从本地数据筛选"""
        print(f"🔍 获取火车票数据: {origin} → {destination}")
        
        # 从本地数据中筛选
        filtered_trains = []
        for train in self.train_data:
            if (train['origin'] == origin and train['destination'] == destination):
                filtered_trains.append(train)
        
        print(f"✅ 从本地数据找到 {len(filtered_trains)} 条火车票数据")
        return filtered_trains
    
    def get_nearby_cities_data(self, origin, destination, date=None):
        """获取周边城市对比数据"""
        print(f"🔍 获取周边城市对比数据: {origin} → {destination}")
        
        all_results = []
        
        # 获取原始城市数据
        flights = self.get_flight_data(origin, destination, date)
        trains = self.get_train_data(origin, destination, date)
        
        for flight in flights:
            flight['is_nearby'] = False
            flight['nearby_type'] = 'origin'
        for train in trains:
            train['is_nearby'] = False
            train['nearby_type'] = 'origin'
        
        all_results.extend(flights)
        all_results.extend(trains)
        
        # 获取周边城市数据
        nearby_origins = NEARBY_CITIES.get(origin, [])
        nearby_destinations = NEARBY_CITIES.get(destination, [])
        
        # 周边出发城市
        for nearby_origin in nearby_origins[:2]:  # 限制数量
            nearby_flights = self.get_flight_data(nearby_origin, destination, date)
            nearby_trains = self.get_train_data(nearby_origin, destination, date)
            
            for flight in nearby_flights:
                flight['is_nearby'] = True
                flight['nearby_type'] = 'origin'
                flight['nearby_city'] = nearby_origin
                flight['origin'] = f"{nearby_origin}({origin}附近)"
            
            for train in nearby_trains:
                train['is_nearby'] = True
                train['nearby_type'] = 'origin'
                train['nearby_city'] = nearby_origin
                train['origin'] = f"{nearby_origin}({origin}附近)"
            
            all_results.extend(nearby_flights)
            all_results.extend(nearby_trains)
        
        # 周边到达城市
        for nearby_dest in nearby_destinations[:2]:  # 限制数量
            nearby_flights = self.get_flight_data(origin, nearby_dest, date)
            nearby_trains = self.get_train_data(origin, nearby_dest, date)
            
            for flight in nearby_flights:
                flight['is_nearby'] = True
                flight['nearby_type'] = 'destination'
                flight['nearby_city'] = nearby_dest
                flight['destination'] = f"{nearby_dest}({destination}附近)"
            
            for train in nearby_trains:
                train['is_nearby'] = True
                train['nearby_type'] = 'destination'
                train['nearby_city'] = nearby_dest
                train['destination'] = f"{nearby_dest}({destination}附近)"
            
            all_results.extend(nearby_flights)
            all_results.extend(nearby_trains)
        
        print(f"✅ 周边城市对比完成，共 {len(all_results)} 条结果")
        return all_results
    
    def smart_sort(self, data, sort_type='comprehensive'):
        """智能排序"""
        print(f"🧠 智能排序: {sort_type}")
        
        if sort_type == 'price':
            # 按价格排序
            data.sort(key=lambda x: x.get('price', 0))
        elif sort_type == 'time':
            # 按时间排序
            data.sort(key=lambda x: self._parse_time(x.get('dep_time', '')))
        elif sort_type == 'comprehensive':
            # 综合排序：价格权重60%，时间权重40%
            for item in data:
                price_score = 1000 - item.get('price', 0)  # 价格越低分数越高
                time_score = self._calculate_time_score(item.get('dep_time', ''))
                item['smart_score'] = price_score * 0.6 + time_score * 0.4
            
            data.sort(key=lambda x: x.get('smart_score', 0), reverse=True)
        
        # 优先显示非周边城市的结果
        data.sort(key=lambda x: x.get('is_nearby', False))
        
        print(f"✅ 智能排序完成")
        return data
    
    def _parse_time(self, time_str):
        """解析时间字符串"""
        try:
            if time_str:
                return datetime.strptime(str(time_str), '%Y-%m-%d %H:%M')
        except:
            pass
        return datetime.now()
    
    def _calculate_time_score(self, time_str):
        """计算时间分数"""
        try:
            if time_str:
                time_obj = datetime.strptime(str(time_str), '%Y-%m-%d %H:%M')
                hour = time_obj.hour
                # 早上8-10点，下午2-4点分数最高
                if 8 <= hour <= 10 or 14 <= hour <= 16:
                    return 100
                elif 6 <= hour <= 8 or 10 <= hour <= 14 or 16 <= hour <= 18:
                    return 80
                else:
                    return 60
        except:
            pass
        return 50
    
    def _parse_flight_data(self, data, origin, destination):
        """解析机票数据"""
        flights = []
        
        try:
            result = data.get('result', {})
            flight_list = result.get('flightInfo', [])
            
            for item in flight_list:
                try:
                    flight = {
                        'type': 'flight',
                        'flight_number': item.get('flightNo', ''),
                        'airline': item.get('airlineName', ''),
                        'origin': origin,
                        'destination': destination,
                        'dep_time': f"{item.get('departureDate', '')} {item.get('departureTime', '')}",
                        'arr_time': f"{item.get('arrivalDate', '')} {item.get('arrivalTime', '')}",
                        'price': int(item.get('ticketPrice', 0)),
                        'dep_airport': item.get('departureName', ''),
                        'arr_airport': item.get('arrivalName', ''),
                        'aircraft': item.get('aircraftType', ''),
                        'has_stop': '是' if item.get('stops', 0) > 0 else '否',
                        'is_transfer': '否',
                        'duration': item.get('duration', ''),
                        'source': '聚合数据API',
                        'crawl_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                    }
                    
                    if flight['price'] > 0:
                        flights.append(flight)
                        
                except Exception as e:
                    print(f"  ❌ 解析航班条目异常: {e}")
                    continue
            
        except Exception as e:
            print(f"❌ 机票数据解析异常: {e}")
        
        return flights

# 创建API实例
api = FinalSmartTravelAPI()

@app.route('/')
def index():
    """主页"""
    return render_template_string(INDEX_TEMPLATE)

@app.route('/api/status')
def api_status():
    """API状态检查"""
    return jsonify({
        'status': 'success',
        'message': '最终智能化服务器运行正常',
        'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
        'features': [
            '真实机票数据获取（聚合数据API）',
            '本地Excel高铁数据加载',
            '周边城市智能对比',
            '智能排序功能',
            'DeepSeek AI集成'
        ],
        'apis': {
            'flight': 'enabled',
            'train': 'enabled (本地Excel数据)',
            'nearby': 'enabled',
            'smart_sort': 'enabled',
            'deepseek': 'enabled' if api.ai_available else 'disabled'
        },
        'supported_cities': list(CITY_TO_IATA.keys()),
        'nearby_cities': NEARBY_CITIES,
        'train_data_count': len(api.train_data)
    })

@app.route('/api/search', methods=['POST'])
def search_travel():
    """搜索交通方式 - 包含周边城市对比"""
    try:
        data = request.get_json()
        origin = data.get('origin', '')
        destination = data.get('destination', '')
        date = data.get('date', '')
        include_nearby = data.get('include_nearby', True)
        sort_type = data.get('sort_type', 'comprehensive')
        
        if not origin or not destination:
            return jsonify({'error': '请提供出发地和目的地'}), 400
        
        print(f"🔍 搜索请求: {origin} → {destination} ({date})")
        print(f"🔍 包含周边城市: {include_nearby}, 排序方式: {sort_type}")
        
        if include_nearby:
            # 获取包含周边城市的数据
            all_data = api.get_nearby_cities_data(origin, destination, date)
        else:
            # 只获取原始城市数据
            flights = api.get_flight_data(origin, destination, date)
            trains = api.get_train_data(origin, destination, date)
            all_data = flights + trains
        
        # 智能排序
        all_data = api.smart_sort(all_data, sort_type)
        
        # 统计信息
        flights_count = len([x for x in all_data if x.get('type') == 'flight'])
        trains_count = len([x for x in all_data if x.get('type') == 'train'])
        nearby_count = len([x for x in all_data if x.get('is_nearby', False)])
        
        result = {
            'status': 'success',
            'data': all_data,
            'total': len(all_data),
            'flights': flights_count,
            'trains': trains_count,
            'nearby': nearby_count,
            'sort_type': sort_type,
            'include_nearby': include_nearby,
            'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        }
        
        print(f"✅ 搜索完成: 找到 {len(all_data)} 条结果（航班 {flights_count}，火车 {trains_count}，周边 {nearby_count}）")
        return jsonify(result)
        
    except Exception as e:
        print(f"❌ 搜索异常: {e}")
        return jsonify({'error': str(e)}), 500

@app.route('/api/cities')
def get_cities():
    """获取支持的城市列表"""
    return jsonify({
        'status': 'success',
        'cities': list(CITY_TO_IATA.keys()),
        'nearby_cities': NEARBY_CITIES,
        'total': len(CITY_TO_IATA)
    })

# HTML模板
INDEX_TEMPLATE = '''
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能交通规划助手 - 最终版</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 1400px;
            margin: 0 auto;
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }
        
        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
        }
        
        .header p {
            font-size: 1.2em;
            opacity: 0.9;
        }
        
        .search-section {
            padding: 30px;
            background: #f8f9fa;
        }
        
        .search-form {
            display: grid;
            grid-template-columns: 1fr 1fr 1fr auto;
            gap: 20px;
            align-items: end;
        }
        
        .form-group {
            display: flex;
            flex-direction: column;
        }
        
        .form-group label {
            font-weight: bold;
            margin-bottom: 8px;
            color: #333;
        }
        
        .form-group input, .form-group select {
            padding: 12px;
            border: 2px solid #e1e5e9;
            border-radius: 8px;
            font-size: 16px;
            transition: border-color 0.3s;
        }
        
        .form-group input:focus, .form-group select:focus {
            outline: none;
            border-color: #667eea;
        }
        
        .search-btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 12px 30px;
            border-radius: 8px;
            font-size: 16px;
            font-weight: bold;
            cursor: pointer;
            transition: transform 0.2s;
        }
        
        .search-btn:hover {
            transform: translateY(-2px);
        }
        
        .options-section {
            padding: 20px 30px;
            background: #f0f2f5;
            border-top: 1px solid #e1e5e9;
        }
        
        .options-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            align-items: center;
        }
        
        .option-group {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .option-group label {
            font-weight: bold;
            color: #333;
        }
        
        .option-group input[type="checkbox"] {
            width: 18px;
            height: 18px;
        }
        
        .option-group select {
            padding: 8px;
            border: 2px solid #e1e5e9;
            border-radius: 6px;
            font-size: 14px;
        }
        
        .results-section {
            padding: 30px;
        }
        
        .results-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        
        .results-count {
            font-size: 1.2em;
            font-weight: bold;
            color: #333;
        }
        
        .results-stats {
            display: flex;
            gap: 15px;
            font-size: 0.9em;
            color: #666;
        }
        
        .results-list {
            display: grid;
            gap: 15px;
        }
        
        .result-item {
            background: white;
            border: 2px solid #e1e5e9;
            border-radius: 12px;
            padding: 20px;
            transition: all 0.3s;
            cursor: pointer;
            position: relative;
        }
        
        .result-item:hover {
            border-color: #667eea;
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(102, 126, 234, 0.15);
        }
        
        .result-item.nearby {
            border-left: 5px solid #ff9800;
            background: #fff8e1;
        }
        
        .result-item.nearby::before {
            content: "周边城市";
            position: absolute;
            top: 10px;
            right: 10px;
            background: #ff9800;
            color: white;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
        }
        
        .result-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }
        
        .result-type {
            display: flex;
            align-items: center;
            gap: 8px;
            font-weight: bold;
            font-size: 1.1em;
        }
        
        .result-price {
            font-size: 1.5em;
            font-weight: bold;
            color: #e74c3c;
        }
        
        .result-details {
            display: grid;
            grid-template-columns: 1fr 1fr 1fr;
            gap: 15px;
            margin-bottom: 15px;
        }
        
        .detail-item {
            text-align: center;
        }
        
        .detail-label {
            font-size: 0.9em;
            color: #666;
            margin-bottom: 5px;
        }
        
        .detail-value {
            font-weight: bold;
            color: #333;
        }
        
        .result-meta {
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 0.9em;
            color: #666;
        }
        
        .loading {
            text-align: center;
            padding: 40px;
            font-size: 1.2em;
            color: #666;
        }
        
        .error {
            background: #fee;
            color: #c33;
            padding: 15px;
            border-radius: 8px;
            margin: 20px 0;
        }
        
        .success {
            background: #efe;
            color: #3c3;
            padding: 15px;
            border-radius: 8px;
            margin: 20px 0;
        }
        
        .api-status {
            position: fixed;
            top: 20px;
            right: 20px;
            background: #4CAF50;
            color: white;
            padding: 10px 20px;
            border-radius: 25px;
            font-size: 14px;
            z-index: 1000;
        }
        
        .city-hint {
            font-size: 0.9em;
            color: #666;
            margin-top: 5px;
        }
        
        @media (max-width: 768px) {
            .search-form {
                grid-template-columns: 1fr;
            }
            
            .options-grid {
                grid-template-columns: 1fr;
            }
            
            .result-details {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="api-status" id="apiStatus">API连接正常</div>
    
    <div class="container">
        <div class="header">
            <h1>🚀 智能交通规划助手</h1>
            <p>使用真实Excel高铁数据 + 聚合数据API机票</p>
        </div>
        
        <div class="search-section">
            <form class="search-form" id="searchForm">
                <div class="form-group">
                    <label for="origin">出发地</label>
                    <input type="text" id="origin" name="origin" placeholder="请输入出发城市" required>
                    <div class="city-hint">支持：北京、上海、广州、深圳、大连、合肥等</div>
                </div>
                <div class="form-group">
                    <label for="destination">目的地</label>
                    <input type="text" id="destination" name="destination" placeholder="请输入到达城市" required>
                    <div class="city-hint">支持：北京、上海、广州、深圳、大连、合肥等</div>
                </div>
                <div class="form-group">
                    <label for="date">出发日期</label>
                    <input type="date" id="date" name="date" required>
                </div>
                <button type="submit" class="search-btn">🔍 智能搜索</button>
            </form>
        </div>
        
        <div class="options-section">
            <div class="options-grid">
                <div class="option-group">
                    <input type="checkbox" id="includeNearby" checked>
                    <label for="includeNearby">包含周边城市对比</label>
                </div>
                <div class="option-group">
                    <label for="sortType">排序方式：</label>
                    <select id="sortType">
                        <option value="comprehensive">智能综合排序</option>
                        <option value="price">按价格排序</option>
                        <option value="time">按时间排序</option>
                    </select>
                </div>
            </div>
        </div>
        
        <div class="results-section">
            <div id="resultsContainer">
                <div class="loading" id="loadingMessage" style="display: none;">
                    🧠 正在智能搜索中，请稍候...
                </div>
                <div id="resultsContent"></div>
            </div>
        </div>
    </div>

    <script>
        // 设置默认日期为明天
        document.getElementById('date').value = new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString().split('T')[0];
        
        // 搜索表单提交
        document.getElementById('searchForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const origin = document.getElementById('origin').value;
            const destination = document.getElementById('destination').value;
            const date = document.getElementById('date').value;
            const includeNearby = document.getElementById('includeNearby').checked;
            const sortType = document.getElementById('sortType').value;
            
            if (!origin || !destination) {
                alert('请填写出发地和目的地');
                return;
            }
            
            await searchTravel(origin, destination, date, includeNearby, sortType);
        });
        
        // 搜索交通方式
        async function searchTravel(origin, destination, date, includeNearby, sortType) {
            const loadingMessage = document.getElementById('loadingMessage');
            const resultsContent = document.getElementById('resultsContent');
            
            loadingMessage.style.display = 'block';
            resultsContent.innerHTML = '';
            
            try {
                const response = await fetch('/api/search', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        origin: origin,
                        destination: destination,
                        date: date,
                        include_nearby: includeNearby,
                        sort_type: sortType
                    })
                });
                
                const data = await response.json();
                
                if (data.status === 'success') {
                    displayResults(data.data, data.total, data.flights, data.trains, data.nearby);
                } else {
                    showError(data.error || '搜索失败');
                }
            } catch (error) {
                showError('网络错误：' + error.message);
            } finally {
                loadingMessage.style.display = 'none';
            }
        }
        
        // 显示结果
        function displayResults(results, total, flights, trains, nearby) {
            if (results.length === 0) {
                resultsContent.innerHTML = '<div class="error">未找到相关交通信息</div>';
                return;
            }
            
            let html = `
                <div class="results-header">
                    <div class="results-count">找到 ${total} 条结果</div>
                    <div class="results-stats">
                        <span>✈️ 航班 ${flights} 条</span>
                        <span>🚄 火车 ${trains} 条</span>
                        <span>📍 周边城市 ${nearby} 条</span>
                    </div>
                </div>
                <div class="results-list">
            `;
            
            results.forEach((item, index) => {
                const typeIcon = item.type === 'flight' ? '✈️' : '🚄';
                const typeName = item.type === 'flight' ? '航班' : '火车';
                const number = item.flight_number || item.train_number || '';
                const depTime = item.dep_time || '';
                const arrTime = item.arr_time || '';
                const duration = item.duration || '';
                const price = item.price || 0;
                const isNearby = item.is_nearby || false;
                
                html += `
                    <div class="result-item ${isNearby ? 'nearby' : ''}" onclick="selectResult(${index})">
                        <div class="result-header">
                            <div class="result-type">
                                <span>${typeIcon}</span>
                                <span>${typeName} ${number}</span>
                            </div>
                            <div class="result-price">¥${price}</div>
                        </div>
                        <div class="result-details">
                            <div class="detail-item">
                                <div class="detail-label">出发时间</div>
                                <div class="detail-value">${depTime}</div>
                            </div>
                            <div class="detail-item">
                                <div class="detail-label">到达时间</div>
                                <div class="detail-value">${arrTime}</div>
                            </div>
                            <div class="detail-item">
                                <div class="detail-label">行程时间</div>
                                <div class="detail-value">${duration}</div>
                            </div>
                        </div>
                        <div class="result-meta">
                            <span>数据源：${item.source || '未知'}</span>
                            <span>更新时间：${item.crawl_time || ''}</span>
                        </div>
                    </div>
                `;
            });
            
            html += '</div>';
            resultsContent.innerHTML = html;
        }
        
        // 选择结果
        function selectResult(index) {
            const item = results[index];
            alert(`已选择：${item.type === 'flight' ? '航班' : '火车'} ${item.flight_number || item.train_number} - ¥${item.price}`);
        }
        
        // 显示错误
        function showError(message) {
            const resultsContent = document.getElementById('resultsContent');
            resultsContent.innerHTML = `<div class="error">${message}</div>`;
        }
        
        // 检查API状态
        async function checkApiStatus() {
            try {
                const response = await fetch('/api/status');
                const data = await response.json();
                
                if (data.status === 'success') {
                    document.getElementById('apiStatus').textContent = 'API连接正常';
                    document.getElementById('apiStatus').style.background = '#4CAF50';
                } else {
                    document.getElementById('apiStatus').textContent = 'API连接异常';
                    document.getElementById('apiStatus').style.background = '#f44336';
                }
            } catch (error) {
                document.getElementById('apiStatus').textContent = 'API连接失败';
                document.getElementById('apiStatus').style.background = '#f44336';
            }
        }
        
        // 页面加载时检查API状态
        checkApiStatus();
        
        // 每30秒检查一次API状态
        setInterval(checkApiStatus, 30000);
    </script>
</body>
</html>
'''

if __name__ == '__main__':
    print("🚀 启动最终智能化服务器")
    print("=" * 60)
    print("🔧 包含周边城市对比功能")
    print("🧠 包含智能排序功能")
    print("📊 使用真实Excel高铁数据")
    print("📡 使用聚合数据API获取机票")
    print("=" * 60)
    
    app.run(host='0.0.0.0', port=5004, debug=True)